#include "stdafx.h"
#include "common.h"
#include "math.h"
#define PI 0.01


void updateGradient(node &Node) {
	unsigned int i;
	float tmp;
	//demand
	for (i=0; i<Node.demand_nums; i++){
		tmp = Node.demand[i]+Node.stepsize*Node.demand_delta[i];
		Node.demand_gradient[i] = CONSTANT_P*(1/(Node.demand_limit[i].up-tmp)
												    -1/(tmp-Node.demand_limit[i].down));
		Node.demand_gradient[i] += 2*CONSTANT_ALPHA*tmp-Node.demand_para[i];
	}

	//generator
	for (i=0; i<Node.generator_nums; i++) {
		tmp = Node.generator[i]+Node.stepsize*Node.generator_delta[i];
		Node.generator_gradient[i] = 2*Node.generator_para[i]*tmp-CONSTANT_P*(1/tmp
										-1/(Node.generator_limit[i].up-Node.generator[i]));
	}

	//flow
	for (i=0; i<Node.oneHopNbr_nums; i++) {
		if (Node.oneHopNbr_flow_direction[i] == 1) {
			tmp = Node.oneHopNbr_flow[i]+Node.stepsize*Node.oneHopNbr_flow_delta[i];
			Node.oneHopNbr_flow_gradient[i] = 2*PI*Node.oneHopNbr_flow[i]/Node.oneHopNbr_Susc[i]
				-CONSTANT_P*(1/(Node.oneHopNbr_flow_limit[i].up+tmp)
				-1/(Node.oneHopNbr_flow_limit[i].up+tmp));
		}
		else {
			Node.oneHopNbr_flow_gradient[i] = 0;
		}
	}

}

void updateHassion(node &Node) {
	unsigned int i;
	float tmp;

	//demand
	for (i=0; i<Node.demand_nums; i++) {
		tmp = Node.demand[i]+Node.stepsize*Node.demand_delta[i];
		Node.demand_hassion[i] = CONSTANT_P*(pow((Node.demand_limit[i].up-tmp),-2)
											 +pow((tmp-Node.demand_limit[i].down),-2));
		Node.demand_hassion[i] += 2*CONSTANT_ALPHA;

	}

	//generator
	for (i=0; i<Node.generator_nums; i++) {
		tmp = Node.generator[i]+Node.stepsize*Node.generator_delta[i];
		Node.generator_hassion[i] = 2*Node.generator_para[i]+CONSTANT_P*(pow(tmp,-2)
									+pow((Node.generator_limit[i].up-tmp),-2));
	}

	//flow
	for (i=0; i<Node.oneHopNbr_nums; i++) {
		if (Node.oneHopNbr_flow_direction[i] == 1) {
			tmp = Node.oneHopNbr_flow[i]+Node.stepsize*Node.oneHopNbr_flow_delta[i];
			Node.oneHopNbr_flow_hassion[i] = 2*PI/Node.oneHopNbr_Susc[i]
				+CONSTANT_P/(pow((Node.oneHopNbr_flow_limit[i].up+tmp),2)
				+pow((Node.oneHopNbr_flow_limit[i].up-tmp),2));
		}
		else {
			Node.oneHopNbr_flow_hassion[i] = 0;
		}
	}
}

